<?php
/*
 * @Author: 孙开源 && sunkaiyuan@namenode.cn
 * @Date: 2023-04-12 16:45:39
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @LastEditTime: 2023-04-24 15:20:01
 * @Description: 
 * 
 */
namespace szzhijing\Kernel\Services;

use szzhijing\Kernel\Exceptions\InvalidCredentialsException;
use szzhijing\Kernel\Client;
use function szzhijing\tap;
use szzhijing\Kernel\Traits\ResponseCastable;

class AccessToken
    {
    use ResponseCastable;

    /**
     * @var \szzhijing\Application
     */
    protected $app;

    /**
     * AccessToken constructor.
     *
     * @param \szzhijing\Application
     */
    public function __construct($app)
        {
        $this->app = $app;
        }

    /**
     * 获取 AccessToken缓存
     *
     * @return string
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function getToken()
        {
        if ($value = $this->app->cacher->get("access_token")) {
            return $this->app->cacher->get("token_type") . " {$value}";
            }
        else
            return $this->refresh();
        }


    /**
     * @description: granteCode换accessToken
     * @param string $clientId
     * @param string $grantCode
     * @param string $password
     * @return array
     */
    public function getAccessToken($clientId, $client_secret)
        {
        return $this->app->OIDC->token($clientId, $client_secret);
        }

    /**
     * @description: 刷新 失效 AccessToken
     * @return string
     */
    public function refresh()
        {
        $clientId      = $this->app->config->get('clientId');
        $client_secret = $this->app->config->get('clientSecret');
        $response      = $this->getAccessToken($clientId, $client_secret);
        return $this->saveCache($response);
        }

    /**
     * @description: 保存token 到缓存
     * @param array $response
     * @return string
     */
    public function saveCache($response)
        {
        // $response = $response['result'];
        // if (isset($response['successful']) && true == $response['successful']) {
        //     throw new InvalidCredentialsException(json_encode($response));
        //     }
        $this->app->cacher->set("access_token", $response['access_token'], $response['expires_in']);
        $this->app->cacher->set("client_id", $response['client_id'], $response['expires_in']);
        $this->app->cacher->set("token_type", $response['token_type'], $response['expires_in']);
        return "{$response['token_type']} {$response['access_token']}";

        }

    }